import socket
import struct
import sys
from dataStruct import *

class senderUDPConn():
    def __init__(self, host, port):
        self.addr = (host, port)
        self.host = host
        self.port = port
        self.socketSetup()
        
    def socketSetup(self):
        try:
            self.sUDPSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
            self.sUDPSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        except:
            print "could not connect to %s on port %s" % (self.host, self.port)
            return
        
    def sendData(self, data):
        self.sUDPSock.sendto(data, self.addr)
    
    def close(self):
        self.sUDPSock.close()


class reciverUDPConn():
    def __init__(self, host, port, buffSize):
        self.host = host
        self.port = port
        self.addr = (host, port) 
        self.socketSetup()
        self.buffSize = buffSize
    
    def socketSetup(self):
        self.rUDPSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        try:
            self.rUDPSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.rUDPSock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
            self.rUDPSock.settimeout(30)
        except:
            print "Socket options failed"
        self.rUDPSock.bind((self.host, self.port))
        mreq = struct.pack("4sl", socket.inet_aton(self.host), socket.INADDR_ANY)        
        self.rUDPSock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
  
    def recData(self):
        try:
            data = self.rUDPSock.recv(self.buffSize)
        except:
            data = "Error"
        return data
        
    def close(self):
        self.rUDPSock.close()
        

        
        
        